<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属清单" prop="shopListId">
        <el-select
          v-model="queryParams.shopListId"
          placeholder="请选择清单"
          clearable
          filterable
        >
          <el-option
            v-for="dict in shopList"
            :key="dict.listId"
            :label="dict.listName"
            :value="dict.listId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:product:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:product:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:product:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:product:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Check"
          :disabled="multiple"
          @click="handleComplete"
          v-hasPermi="['manage:product:edit']"
          >完成</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="productList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column
        label="商品图片"
        align="center"
        prop="productImage"
        width="100"
      >
        <template #default="scope">
          <image-preview
            :src="scope.row.productImage"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="购买数量" align="center" prop="buyCount">
        <template #default="scope">
          <span style="display: flex; justify-content: center">
            <span>{{ scope.row.buyCount }}&nbsp;</span>
            <dict-tag :options="product_unit" :value="scope.row.unitId" />
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="单位" align="center" prop="unitId" >
        <template #default="scope">
          <dict-tag :options="product_unit" :value="scope.row.unitId"/>
        </template>
      </el-table-column> -->
      <el-table-column label="完成状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status == 0 ? 'danger' : ''">
            <dict-tag :options="product_status" :value="scope.row.status" />
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属清单" align="center" prop="listName" />
      <el-table-column
        label="录入时间"
        align="center"
        prop="createTime"
        width="160"
        sortable
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Check"
            @click="handleComplete(scope.row)"
            v-hasPermi="['manage:product:edit']"
            >完成</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:product:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:product:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改清单详情对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="productImage">
          <image-upload v-model="form.productImage" :limit="1" />
        </el-form-item>
        <div class="flex-row">
          <!-- 购买数量 -->
          <el-form-item label="购买数量" prop="buyCount" class="flex-item">
            <el-input-number
              v-model="form.buyCount"
              :min="0"
              :precision="1"
              :step="0.1"
            />
          </el-form-item>

          <!-- 单位 -->
          <el-form-item label="单位" prop="unitId" class="flex-item">
            <el-select v-model="form.unitId" placeholder="请选择单位" clearable>
              <el-option
                v-for="dict in product_unit"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="所属清单" prop="shopListId">
          <el-select
            v-model="form.shopListId"
            placeholder="请选择清单"
            clearable
          >
            <el-option
              v-for="dict in shopList"
              :key="dict.listId"
              :label="dict.listName"
              :value="dict.listId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import { listProduct, getProduct, delProduct, addProduct, updateProduct, completeProducts } from "@/api/manage/product"
import { listBuylist } from "@/api/manage/buylist"
import { useRoute } from "vue-router"
import { ref, onMounted, watch } from "vue"

const { proxy } = getCurrentInstance()
const { product_unit } = proxy.useDict('product_unit')
const { product_status } = proxy.useDict('product_status')

const productList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const shopList = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: null,
    status: null,
    shopListId: null,
  },
  rules: {
    productName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    buyCount: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
    unitId: [
      { required: true, message: "请选择单位", trigger: "change" }
    ],
    shopListId: [
      { required: true, message: "请选择所属清单", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)
const route = useRoute()

// 获取清单列表
async function getBuyList () {
  try {
    const response = await listBuylist()
    shopList.value = response.rows
    console.log("shopList", shopList.value)
    loading.value = false
    // 设置查询参数
    const listIdFromRoute = route.query.listId
    // 检查 listId 是否存在于 shopList 中
    const foundList = shopList.value.find(list => list.listId === parseInt(listIdFromRoute))
    if (foundList) {
      queryParams.value.shopListId = foundList.listId
    }
  } catch (error) {
    console.error("获取清单列表失败:", error)
    loading.value = false
  }
}

// 监听路由参数变化
watch(
  () => route.query.listId,
  (newListId, oldListId) => {
    if (newListId !== oldListId) {
      const foundList = shopList.value.find(list => list.listId === parseInt(newListId))
      if (foundList) {
        queryParams.value.shopListId = foundList.listId
        // 重新获取列表数据
        getList()
      }
    }
  },
  { immediate: true }
)

/** 查询清单详情列表 */
function getList () {
  loading.value = true
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows
    console.log("productList", productList.value)
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel () {
  open.value = false
  reset()
}

// 表单重置
function reset () {
  form.value = {
    productId: null,
    productName: null,
    productImage: null,
    buyCount: null,
    unitId: null,
    status: null,
    shopListId: null
  }
  proxy.resetForm("productRef")
}

/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery () {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange (selection) {
  ids.value = selection.map(item => item.productId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd () {
  reset()
  open.value = true
  title.value = "添加清单详情"
}

/** 修改按钮操作 */
function handleUpdate (row) {
  reset()
  const _productId = row.productId || ids.value
  getProduct(_productId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改清单详情"
  })
}

/** 修改按钮操作 */
function handleComplete (row) {
  reset()
  const _productId = row.productId || ids.value
  if (Array.isArray(_productId) && _productId.length > 0) {
    completeProducts(_productId).then(response => {
      proxy.$modal.msgSuccess("操作成功")
      getList()
    })
  } else {
    getProduct(_productId).then(response => {
      form.value = response.data
      form.value.status = 1
      updateProduct(form.value).then(response => {
        proxy.$modal.msgSuccess("操作成功")
        getList()
      })
    })
  }
}

/** 提交按钮 */
function submitForm () {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      if (form.value.productId != null) {
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete (row) {
  const _productIds = row.productId || ids.value
  const delName = _productIds.length >= 1 ? '选中的商品' : row.productName
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function () {
    return delProduct(_productIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport () {
  proxy.download('manage/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

// 确保在首次加载时也设置正确的 shopListId
onMounted(async () => {
  await getBuyList()
  const listIdFromRoute = route.query.listId
  if (listIdFromRoute) {
    const foundList = shopList.value.find(list => list.listId === parseInt(listIdFromRoute))
    if (foundList) {
      queryParams.value.shopListId = foundList.listId
    }
  }
  getList() // 获取初始列表
});
</script>

<style scoped>
.flex-row {
  display: flex;
}

.flex-item {
  flex: 1; /* 让两个项目平均分配可用空间 */
}

/* 最后一个子元素不需要右边距 */
.flex-row .flex-item:last-child {
  margin-right: 0;
}
</style>